package org.shuzhou.gendata;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class PeopleSocket {
    private static final int PORT = 9999;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Server is listening on port " + PORT);

            while (true) {
                sendSocketData(serverSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void sendSocketData(ServerSocket serverSocket) throws IOException {
        Socket clientSocket = serverSocket.accept();
        System.out.println("Client connected: " + clientSocket.getInetAddress());

        OutputStream outputStream = clientSocket.getOutputStream();

        while (true) {
            String data = generateData();
            // 给定数据格式为"姓名,性别,民族,身份证号,出生日期,电话号码,电子邮件地址,地址"
            byte[] bytes = (data + "\n").getBytes(StandardCharsets.UTF_8);
            
            outputStream.write(bytes);
            outputStream.flush();
            System.out.println("Sent data: " + data);
            // 可根据需要添加换行符等分隔符
            // outputStream.write("\n".getBytes(StandardCharsets.UTF_8));

            try {
                // 随机等待一段时间再发送数据
                Thread.sleep(new Random().nextInt(5000) + 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }

        // bufferedReader.close();
        clientSocket.close();
        System.out.println("Data sent to client.");
    }

    private static String generateData() {
        // 随机生成数据
        String[] firstNames = {"王", "万", "包", "庞"};
        String[] lastNames = {"矗馨", "俊伟", "弓泰", "金豪"};
        String[] sexes = {"女", "男", "男", "女"};
        String[] ethnicities = {"汉族", "阿昌族", "东乡族", "汉族"};
        String[] ids = {"411424195001010028", "410300195001010012", "210122195001010012", "210881195001010029"};
        String[] birthDates = {"19500101", "19500101", "19500101", "19500101"};
        String[] phoneNumbers = {"150977754190", "147187543706", "152097094505", "137423581749"};
        String[] emailAddresses = {"kk4jlw850x@sina.com", "l6enhmxw6e@gmail.com", "edifgq62im@gmail.com", "0s1x9wxuly@163.com"};
        String[] addresses = {"甘肃省临夏回族自治州和政县CNR路884号", "河北省邢台市巨鹿县JZV路2号", "湖北省荆州市监利县KWX路712号", "河北省邢台市PTZ路532号"};

        int index = new Random().nextInt(4);
        return firstNames[index] + lastNames[index] + "," + sexes[index] + "," + ethnicities[index] + "," +
                ids[index] + "," + birthDates[index] + "," + phoneNumbers[index] + "," +
                emailAddresses[index] + "," + addresses[index];
    }
}